<?php
declare(strict_types=1);

namespace App\Utils;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use Hyperf\Utils\Context;

/**
 * @Description 富文本
 * @author wuxian
 * @since 2020-04-15
 */
class RichTextUtil
{
    /**
     * 对富文本信息中的数据
     * 匹配出所有的 <img> 标签的 src属性
     *  $content 富文本字符串
     * return array
     */
    public static function getPatternMatchImages($content = "")
    {
        //$contentStr = htmlspecialchars($contentStr);
        $content_decode = htmlspecialchars_decode($content);
        $imgSrcArr = [];
        //首先将富文本字符串中的 img 标签进行匹配
        $pattern_imgTag = '/<img\b.*?(?:\>|\/>)/i';
        preg_match_all($pattern_imgTag, $content, $matchIMG);
        if (isset($matchIMG[0])) {
            foreach ($matchIMG[0] as $key => $imgTag) {
                //进一步提取 img标签中的 src属性信息
                $pattern_src = '/\bsrc\b\s*=\s*[\'\"]?([^\'\"]*)[\'\"]?/i';
                preg_match_all($pattern_src, $imgTag, $matchSrc);
                if (isset($matchSrc[1])) {
                    foreach ($matchSrc[1] as $src) {
                        //将匹配到的src信息压入数组
                        $imgSrcArr[] = $src;
                    }
                }
            }
        }
        //$pattern= '/<img\b.+\bsrc\b\s*=\s*[\'\"]([^\'\"]*)[\'\"]/iU';
        return $imgSrcArr;
    }

    // 文本里面的图片链接替换本地
    public static function replaceImgUrl($content = "", $imgSrcArr = [])
    {
        if (empty($content) || empty($imgSrcArr)) {
            return $content;
        }
        foreach ($imgSrcArr as $img_url) {
            $download_img = static::downloadImg($img_url);
            // 替换富文本的内容
            $content = str_replace($img_url, $download_img, $content);
        }
        return $content;
    }

    // 远程图片下载
    public static function downloadImg($url='')
    {
        if (empty($url)) {
            return '';
        } else {
            $img_info = getimagesize($url);
            $suffix = static::mineSuffix()[$img_info['mime'] ?? 'image/png'];
            $fileName = uniqid() . $suffix;
            $file_url = '/images/'.date('Ymd').'/';
            $fileDir = config('server.settings.document_root').$file_url;
            static::mkdir($fileDir);
            $save_path = $fileDir.$fileName;
            $readStream = fopen($url, 'r');
            $wtriteStream = fopen($save_path, 'w');
            stream_copy_to_stream($readStream, $wtriteStream);
            return env('WEB_HOST', '127.0.0.1:9501').$file_url .$fileName;
        }
    }

    //创建目录
    public static function mkdir($dir)
    {
        is_dir($dir) || mkdir($dir, 0777, true);
    }

    //图片的mine对应的后缀
    public static function mineSuffix()
    {
        return [
            'image/png' => '.png',
            'image/jpeg' => '.jpg',
            'image/x-ms-bmp' => '.bmp',
            'image/gif' => '.gif',
            'image/tiff' => '.tif',
        ];
    }
}
